package com.jianzhi.job.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.core.common.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


@Controller
@RequestMapping("/uploadAction")
public class UploadAction extends BaseController  {
    @RequestMapping(params = "method=index", method = RequestMethod.GET)
    public String index() {
        return "upload/index";
    }
    @RequestMapping(params = "upload")
    public @ResponseBody String upload(HttpServletRequest request, HttpServletResponse response) {
//        request = new MulpartRequestWrapper(request);
        
        String responseStr="";  
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
        //获取前台传值  
        String[] userNames = multipartRequest.getParameterValues("userName");  
        String[] contents = multipartRequest.getParameterValues("content");  
        String userName="";  
        String content="";  
        if(userNames!=null){  
            userName=userNames[0];  
        }  
        if(contents!=null){  
            content=contents[0];  
        }  
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();    
//            String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "\\" + "images\\";    
            String ctxPath=request.getSession().getServletContext().getRealPath("/")+"upload\\stepimages\\"; 
//            String ctxPath= HNAServletContextListener.getSYS_UPLOADPATH_PATH();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");  
//        String ymd = sdf.format(new Date());  
        ctxPath +=  "/";  
        //创建文件夹  
        System.out.println("创建的文件夹:"+ ctxPath);
            File file = new File(ctxPath);    
            if (!file.exists()) {    
                file.mkdirs();    
            }    
            String fileName = null;
            String path=null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {    
                // 上传文件名    
                // System.out.println("key: " + entity.getKey());    
                MultipartFile mf = entity.getValue();    
                fileName = mf.getOriginalFilename();  
               String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();      
               SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
                
//                String strEnc = DesEncrypt.aircrewhealthGetEncString(fileName);// 加密字符串,返回String的密文
//                String strEnc = fileName;
//                String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");// 返回一个随机UUID。
//                String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;
//
//                String newFileName = strEnc + "-" + uuid + (suffix!=null?suffix:"");// 构成新文件名。
                System.out.println("新文件名："+ newFileName);
                
                File uploadFile = new File(ctxPath + newFileName);    
                try {  
                    FileCopyUtils.copy(mf.getBytes(), uploadFile); 
                    path ="upload\\stepimages\\"+newFileName;
                responseStr="上传成功";  
            } catch (IOException e) {  
                responseStr="上传失败";  
                e.printStackTrace();  
            }    
            }   
           System.out.println("return :" +path);
            return path;  
    }
    /**
     * 删除步骤图片文件
     * @param request
     * @return
     */
    @RequestMapping (params="deleteStepImg")
    public  @ResponseBody HashMap<String, Object> deleteStepImg(HttpServletRequest request, HttpServletResponse response){
    	HashMap<String, Object>  map = new HashMap<String,Object>() ;
    	String path =request.getSession().getServletContext().getRealPath("/")+ request.getParameter("filePath");
    	System.out.println(path);
    	if(deleteFile(path)){
    		map.put("msg", "删除成功！");
    		map.put("status", true);
    	}else{
    		map.put("msg", "删除失败!");
    		map.put("status", false);
    	}
    	return map;
    }
    /** 
     * 删除单个文件 
     * @param   sPath    被删除文件的文件名 
     * @return 单个文件删除成功返回true，否则返回false 
     */  
    public boolean deleteFile(String sPath) {  
      boolean  flag = false;  
      File  file = new File(sPath);  
        // 路径为文件且不为空则进行删除  
        if (file.isFile() && file.exists()) {  
            file.delete();  
            flag = true;  
        }  
        return flag;  
    }  
}